package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.*;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.ibatis.annotations.Param;
import org.aspectj.weaver.ast.Var;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementServiceImpl implements MovementService {
    //注入动态id生成service
    @Autowired
    private RedisPidService redisPidService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveMovement(Movement movement) {
        //生成唯一的动态id
        Long pid = redisPidService.getNextPid(ConstantUtil.MOVEMENT_ID);
        //写入实体类
        movement.setPid(pid);
        mongoTemplate.save(movement);
        //将数据添加道个人动态表
        MyMovement myMovement = new MyMovement();
        myMovement.setPublishId(movement.getId());
        myMovement.setCreated(movement.getCreated());
        mongoTemplate.save(myMovement,ConstantUtil.MOVEMENT_MINE+movement.getUserId());
        //根据好友表将数据录入好友动态表中
        Query query = new Query(
                Criteria.where("userId").is(movement.getUserId())
        );
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //遍历集合
        if (CollectionUtil.isNotEmpty(friends)) {
            for (Friend friend : friends) {
                //建立好友动态类
                Long friendId = friend.getFriendId();
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setPublishId(movement.getId());
                friendMovement.setCreated(movement.getCreated());
                friendMovement.setUserId(movement.getUserId());
                //提交
                mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friendId);

            }
        }


    }
    //查询我的动态
    @Override
    public PageBeanVo findMymovents(Long userId, Integer pageNum, Integer pageSize) {
        //构建查询页
        Integer index = (pageNum - 1) * pageSize;
        //条件查询,获得我的动态
        Query qu = new Query().with(Sort.by(Sort.Order.desc("created"))).skip(index).limit(pageSize);
        List<MyMovement> myMovements = mongoTemplate.find(qu, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);
        List<Movement> movements = new ArrayList<>();
        //遍历集合查询个人动态详情
        if (CollectionUtil.isNotEmpty(myMovements)) {
            for (MyMovement myMovement : myMovements) {
                //获得动态id
                ObjectId publishId = myMovement.getPublishId();
                //根据动态id查询个人动态
                Movement movement = mongoTemplate.findById(publishId, Movement.class);
                if (movement.getState()==1) {
                    movements.add(movement);
                }


            }
        }
        Long totol = mongoTemplate.count(qu,MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);



        return new PageBeanVo(pageNum,pageSize,totol,movements);
    }
//查询好友动态
    @Override
    public PageBeanVo findFrints(Long userid, Integer pageNum, Integer pageSize) {
        //分页其实页
        Integer index =(pageNum-1)*pageSize;
        //创建查询条件
        Query query = new Query(
        ).with(Sort.by(Sort.Order.desc("created"))).skip(index).limit(pageSize);
        //根据userid查询好友表
        List<FriendMovement> friendMovementList = mongoTemplate.find(query,FriendMovement.class,
                ConstantUtil.MOVEMENT_FRIEND+userid);
        ArrayList<Movement> movements = new ArrayList<>();
        //根据还有的id查询好友的所有动态
        //判断列表是否为空
        if (CollectionUtil.isNotEmpty(friendMovementList)) {
            for (FriendMovement friendMovement : friendMovementList) {
                ObjectId publishId = friendMovement.getPublishId();
                //根据动态id查询主表中的动态
                Movement movement = mongoTemplate.findById(publishId, Movement.class);
                if (movement.getState()==1) {
                    // 添加到集合
                    movements.add(movement);
                }
            }

        }
        Long totol = mongoTemplate.count(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userid);
        return new PageBeanVo(pageNum,pageSize,totol,movements);
    }
//查询推荐动态
    @Override
    public PageBeanVo findRecommendMovement(Long userId, Integer pageNum, Integer pageSize) {
        //创建动态条件
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Order.desc("score"))).skip((pageNum - 1) * pageSize).limit(pageSize);
        //查询推荐动态
        List<RecommendMovement> recommendMovements = mongoTemplate.find(query, RecommendMovement.class);
        //创建记过集合
        ArrayList<Movement> movements = new ArrayList<>();
        //判断如果不为空
        if (CollectionUtil.isNotEmpty(recommendMovements)) {
            //遍历集合
            for (RecommendMovement recommendMovement : recommendMovements) {
                ObjectId publishId = recommendMovement.getPublishId();
                //根据动态id，查询
                Movement movement = mongoTemplate.findById(publishId, Movement.class);
                movements.add(movement);
            }

        }
        long totol = mongoTemplate.count(query,RecommendMovement.class);

        return new PageBeanVo(pageNum,pageSize,totol,movements);
    }
//根据动态id查询动态
    @Override
    public Movement findByid(ObjectId objectId) {

        return mongoTemplate.findById(objectId,Movement.class);
    }
    //查询用户所有动态
    @Override
    public PageBeanVo findMovementVoByPage(Integer state, Long userId, Integer pageNum, Integer pageSize) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);
        if (state!=null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        if (userId!=null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        Long total = mongoTemplate.count(query,Movement.class);

        return new PageBeanVo(pageNum,pageSize,total,movementList);
    }
//修改动态
    @Override
    public void updateState(Movement movement) {
        mongoTemplate.save(movement);
    }

}
